package com.manage.func.ordermanagement.returnorder.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.manage.base.bean.CommonResultBean;
import com.manage.base.controller.BaseController;
import com.manage.config.model.Config;
import com.manage.func.ordermanagement.loanorder.model.LoanOrderExcelBean;
import com.manage.func.ordermanagement.loanorder.model.LoanOrderExportQueryBean;
import com.manage.func.ordermanagement.returnorder.model.ReturnOrderBean;
import com.manage.func.ordermanagement.returnorder.model.ReturnOrderBooksBean;
import com.manage.func.ordermanagement.returnorder.model.ReturnOrderExcelBean;
import com.manage.func.ordermanagement.returnorder.model.ReturnOrderExportQueryBean;
import com.manage.func.ordermanagement.returnorder.service.IReturnOrderService;
import com.manage.user.model.User;
import com.manage.util.ExportExcel;

/**
 * 借书单管理
 * 
 * @author xy
 *
 */
@Controller
@RequestMapping("/returnorder")
public class ReturnOrderController extends BaseController {

	private static final long serialVersionUID = 1L;

	static final Logger LOG = LoggerFactory.getLogger(ReturnOrderController.class);

	@Autowired
	private IReturnOrderService returnOrderService;

	// 查询借书单
	@RequestMapping(value = "select", method = RequestMethod.POST)
	@ResponseBody
	public CommonResultBean select(@RequestParam("data") String data) {
		CommonResultBean sys = new CommonResultBean();
		try {
			LOG.info("returnorder select called: " + data);
			ReturnOrderBean bean = fromJson(data, ReturnOrderBean.class);
			// 只过滤出还书单
			bean.setOrdertype(Config.RETURNORDER_TYPE);
			List<ReturnOrderBean> beans = returnOrderService.selectReturnOrderList(bean);
			int size = returnOrderService.selectTotalCount(bean);
			sys.put("returnorder", beans);
			sys.put("size", size);
			// 将确认还书的状态值传给前台，避免在js中判断状态时与固定值比较
			sys.put("orderStatus", Config.ORDER_RETURN);
			return sys;
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			sys.setError();
		}
		return sys;
	}

	// 快递员查询借书单
	@RequestMapping(value = "selectExpress", method = RequestMethod.POST)
	@ResponseBody
	public CommonResultBean selectExpress(@RequestParam("data") String data) {
		CommonResultBean sys = new CommonResultBean();
		try {
			LOG.info("returnorder select called: " + data);
			ReturnOrderBean bean = fromJson(data, ReturnOrderBean.class);
			// 只过滤出还书单
			bean.setOrdertype(Config.RETURNORDER_TYPE);
			// 只过滤出初始还书单
			bean.setStatus(Config.ORDER_FOR_RETURN);
			List<ReturnOrderBean> beans = returnOrderService.selectReturnOrderList(bean);
			int size = returnOrderService.selectTotalCount(bean);
			sys.put("returnorder", beans);
			sys.put("size", size);
			return sys;
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			sys.setError();
		}
		return sys;
	}

	// 图书管理员更新借书单
	@RequestMapping(value = "update", method = RequestMethod.POST)
	@ResponseBody
	public CommonResultBean update(@RequestParam("data") String data, HttpServletRequest request) {
		CommonResultBean sys = new CommonResultBean();
		try {
			LOG.info("returnorder update called: " + data);
			User sysuser = (User) request.getSession().getAttribute(Config.USER_SESSION);
			if (null == sysuser) {
				sys.setErrorMsg("请先登录再进行操作");
				return sys;
			}
			ReturnOrderBean bean = fromJson(data, ReturnOrderBean.class);
			ReturnOrderBooksBean booksBean = new ReturnOrderBooksBean();
			// 更新确认还书状态
			bean.setStatus(Config.ORDER_RETURN);
			booksBean.setOrderNo(bean.getOrderNo());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			booksBean.returnDateInStr = Timestamp.valueOf(sdf.format(new Date()));
			returnOrderService.updateReturnOrder(bean, booksBean);
			sys.setResult_code(Config.SUCCESS);
			sys.setResult_message(Config.SUCCESS_MSG);
			return sys;
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			sys.setError();
		}
		return sys;
	}

	/**
	 * 查询还书单中的书籍
	 * 
	 * @param data
	 * @return
	 */
	@RequestMapping(value = "/books/select", method = RequestMethod.POST)
	@ResponseBody
	public CommonResultBean booksSelect(@RequestParam("data") String data) {
		CommonResultBean sys = new CommonResultBean();
		try {
			LOG.info("returnorder booksSelect called: " + data);
			ReturnOrderBean bean = fromJson(data, ReturnOrderBean.class);
			if (bean != null) {
				List<ReturnOrderBooksBean> beans = returnOrderService.selectReturnOrderBooks(bean);
				sys.put("books", beans);
				return sys;
			}
			sys.setErrorMsg("请求参数为空");
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			sys.setError();
		}
		return sys;
	}

	// 快递员更新快递信息
	@RequestMapping(value = "updateExpressMessage", method = RequestMethod.POST)
	@ResponseBody
	public CommonResultBean updateEpressMessage(@RequestParam("data") String data, HttpServletRequest request) {
		CommonResultBean sys = new CommonResultBean();
		try {
			LOG.info("returnorder updateEpressMessage called: " + data);
			User sysuser = (User) request.getSession().getAttribute(Config.USER_SESSION);
			if (null == sysuser) {
				sys.setErrorMsg("请先登录再进行操作");
				return sys;
			}
			ReturnOrderBean bean = fromJson(data, ReturnOrderBean.class);
			bean.setStatus(Config.RETURNORDER_EXPRESS);
			returnOrderService.updateExpressMessage(bean);
			sys.setResult_code(Config.SUCCESS);
			sys.setResult_message(Config.SUCCESS_MSG);
			return sys;
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			sys.setError();
		}
		return sys;
	}
	/**
	 * 生成excel
	 * 
	 * @param data
	 * @return
	 */
	@RequestMapping(value = "/export", method = RequestMethod.POST)
	@ResponseBody
	public CommonResultBean export(@RequestParam("data") String data,
			HttpServletRequest request) {
		CommonResultBean sys = new CommonResultBean();
		OutputStream out = null; 
		try {
			LOG.info("returnorder export called: " + data);
			ExportExcel<ReturnOrderExcelBean> ex = new ExportExcel<ReturnOrderExcelBean>();
			String[] headers =
			{ "还书单编号", "条形码", "书名", "用户姓名", "用户手机号", "创建日期", "快递单号", "快递公司", "订单状态" };
			ReturnOrderExportQueryBean bean = fromJson(data, ReturnOrderExportQueryBean.class);
			if (bean != null) {
				List<ReturnOrderExcelBean> beans = returnOrderService.selectReturnOrderExcel(bean);
				String fileName = "ReturnOrder.xls";
				String rootPath = super.getWebRootPath(request);
				String fileFullName = rootPath + Config.EXCEL_FILE_PATH + fileName;
				out = new FileOutputStream(fileFullName);
	            ex.exportExcel(headers, beans, out);  
	            out.close();  
	            sys.put("fileName", fileName);
				return sys;
			}
			sys.setErrorMsg("请求参数为空");
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			sys.setError();
		} finally {
			if (out != null){
				try
				{
					out.close();
				}
				catch (IOException e)
				{
					LOG.error(e.getMessage(), e);
					sys.setError();
				}
			}
		}
		return sys;
	}
	/**
	 * 下载excel
	 * 
	 * @param data
	 * @return
	 */
	@RequestMapping(value = "/download", method = RequestMethod.POST)
	@ResponseBody
	public void download(String fileName,HttpServletRequest request,HttpServletResponse response) {
		OutputStream out = null; 
		try {
			String rootPath = super.getWebRootPath(request);
			String fileFullName = rootPath + Config.EXCEL_FILE_PATH + fileName;
//			System.out.println("fileName:" + fileName);
            File file  = new File(fileFullName);
            FileInputStream  in  = new FileInputStream(file);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition",
                       "attachment; filename=" + fileName);
            out = response.getOutputStream();
            byte[] b  = new byte[1024];
            int s =0;
            while((s=in.read(b))>0){
                out.write(b);
            }
            out.flush();
            in.close();
            out.close();
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		} finally {
			if (out != null){
				try
				{
					out.close();
				}
				catch (IOException e)
				{
					LOG.error(e.getMessage(), e);
				}
			}
		}
	}
}
